import json
from flask_restful import Resource
from comment.models.user import User
from flask import current_app,request,g
from comment.utils.sms3 import send_code
import random
from comment.utils.limiter import limiter as lmt
from . import constants
from flask_limiter.util import get_remote_address
from comment.utils.shopping_redis import redis_cenlit
from flask_restful.reqparse import RequestParser
from comment.utils import parser
from comment.models.user import User
from comment.models import db
from comment.utils.token_pyjwt import generate_tokens
from comment.utils.decorators import login_required
class Shopping_user(Resource):
    #在get上添加登录的拦截
    method_decorators = {
        'get':[login_required]
    }
    def get(self):
        current_app.logger.info('我的测试日志')
        return {'hello':'测试'}


class User_SMS(Resource):
    error_message = 'To many request.'

    decorators = [lmt.limit(constants.LIMIT_SMS_CODE_BY_MOBILE,
                            key_func=lambda : request.args['phone'],
                            error_message=error_message),
                  lmt.limit(constants.LIMIT_SMS_CODE_BY_IP,
                            key_func=get_remote_address,
                            error_message=error_message)
                  ]

    def get(self):
        phone = request.args['phone'].strip()
        code = random.randint(1000,9999)
        result = send_code(phone,str(code))
        result = json.loads(result)#把json变成字典
        result['phone'] = phone

        #短信验证码存进redis数据库中 有时效 以便下次验证
        redis_cenlit.setex('shopping:code:{}'.format(phone),constants.LIMIT_SMS_CODE_EXPIRES,code)
        return result


class AuthorizationCodeResource(Resource):
    """
    提交手机号和验证码，开始验证
    """
    def post(self):
        rp = RequestParser()
        rp.add_argument('phone',type=parser.mobie,required=True)
        rp.add_argument('code',type=parser.regex('^\d{4}$'),required=True)
        args = rp.parse_args()
        phone = args.phone
        code = args.code
        print(phone)
        print(code)

        #从redis数据库中得到之前保存的验证码
        key = 'shopping:code:{}'.format(phone)
        try:
            real_code = redis_cenlit.get(key)
        except ConnectionError as e:
            current_app.logger.error(e)
            return {'message':'redis db connect error.'},400
        #开始校验
        # print(real_code)
        if not real_code or real_code.decode() !=code:
            return {'message':'Incalid code.'},400

        return {'phone':phone,'msg':'code success.'}

class RegisterUserResource(Resource):
    '''
    填写账号信息，完成用户的注册
    '''
    def post(self):
        rp = RequestParser()
        rp.add_argument('phone',type=parser.mobie,required=True)
        rp.add_argument('username',required=True)
        rp.add_argument('password',required=True)
        rp.add_argument('email',type=parser.email,required=True)
        args = rp.parse_args()
        phone = args.phone
        username = args.username
        password = args.password
        email = args.email


        #验证用户名是否是唯一的
        u = User.query.filter(User.username==username).first()
        # u = db.session.query(User).filter(User.username==username).first()
        if u:#用户名已经存在
            current_app.logger.info('{}用户名已经存在,请换一个'.format(username))
            return {'message':'The username already exists.'},400
        #把用户信息保存到数据库中

        u = User(username=username,phone=phone,pwd=password,email=email,status = 0)
        db.session.add(u)
        db.session.commit()
        return {'msg':'ok'}



class UserLoginResource(Resource):
    '''
    登录
    '''
    def post(self):
       username =  request.form.get('username')
       password = request.form.get('password')

       if not all([username,password]):
           return {'message':'数据不完整'},401
       user = User.query.filter(User.username==username).first()
       if user:
           if user.check_password(password):
               token = generate_tokens(user.id)
               return {'msg':'Login Success.','token':token,'username':username}
       return {'message':'用户名或者密码错误.'},400

class UserLoginOutResource(Resource):
    '''
    退出登录
    '''
    def post(self):
        if g.user_id:
            g.user_id = None
        return {'msg':'退出登录'}

class IsExistPhoneResource(Resource):
    '''
    判断手机号是否存在
    '''
    def post(self):
        phone = request.form.get('phone')
        user = User.query.filter(User.phone == phone).first()
        if user:
            return {'isExist':True,'message':'此手机号码已经被注册','code':201}
        return {'msg':'手机号可以注册'}